from utils import wechat
from .models import *
import requests, json

class WechatAction(wechat.Wechat):

    def wxEvent(self):
        openid = self.data['FromUserName']
        event = self.data['Event'].strip()
        if event == 'subscribe':
            if 'EventKey' in self.data.keys():
                employee_id = self.data['EventKey'].replace('qrscene_', '')
            else:
                employee_id = None
            member = Members.objects.filter(openid=openid)
            if member:
                member.update(wxStatus=1)
                return self.replayText('欢迎回来！')
            else:
                employee = Employees.objects.get(id=employee_id)
                m = Members.objects.create(openid=openid, employee=employee, wxStatus=1)
                if m:
                    return self.replayText('终于等到你了！')
                else:
                    return self.replayText('error')
        elif event == 'SCAN':
            pass
        elif event == 'unsubscribe':
            Members.objects.filter(openid=openid).update(wxStatus=-1)
        elif event == 'user_get_card': #用户领券行为
            try:
                card = Cards.objects.get(card_id=self.data['CardId'])
                member = Members.objects.get(openid=openid)
                MemberCards.objects.create(card=card, member=member, card_code=self.data['UserCardCode'], card_status=0)
            except Exception as e:
                print(e)
        elif event == 'user_del_card':
            member_card = MemberCards.objects.get(card_code=self.data['UserCardCode'])
            member_card.card_status = -1
            member_card.save()
        elif event == 'submit_membercard_user_info':  #会员卡激活事件
            member_card = MemberCards.objects.get(card_code=self.data['UserCardCode'])
            member_card.card_status = 1
            card = Cards.objects.get(id=member_card.card_id)
            memberInfo = self.getMemberInfo(card.card_id, member_card.card_code)
            member = Members.objects.get(id=member_card.member_id)
            if member.openid == memberInfo['openid']:
                for i in memberInfo['user_info']['common_field_list']:
                    if i['name'] == "USER_FORM_INFO_FLAG_MOBILE":
                        member.mobile = i['value']
                    if i['name'] == "USER_FORM_INFO_FLAG_NAME":
                        member.name = i['value']
                member.save()
            member_card.save()
        else:
            return 'event_error'

    #获取会员卡投放展架
    def card_landingpage(self):
        #self.get_AccessToken()
        accessToken = '12_X_vbpXtr2cHiBeI6c8mJAAdtWyi4dG-N_Gom7BvIDoo7Ez91bHTKtdDcDMMt-t4Xo0ZbNYrphyAD6EOk6OO2iPXaqCwB_eAcKLPig9Am-9mVP-mu-eO8evschIAg8FP6v-UwnmtBE7Io-iC9DCWeAFAIHB'
        url = 'https://api.weixin.qq.com/card/landingpage/create?access_token=' + accessToken
        data = {
            "banner":"https://databackend.quanquaner.com.cn/media/images/zhanjia.png",
            "page_title": "优选会员",
            "can_share": False,
            "scene": "SCENE_MENU",
            "card_list": [
                {"card_id": "pvyUa1tyRddt87Hy4Pgv98gHqZS8","thumb_url": "databackend.quanquaner.com.cn/media/images/logo.jpg"},]
        }
        r = requests.post(url, json.dumps(data))
        print(r.json()['url'])